package com.sumainfor.pc.gmio.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.FileSubufferUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.gmio.dao.RecycleHousingMapper;
import com.sumainfor.pc.gmio.feign.BaseFeignZuul;
import com.sumainfor.pc.gmio.feign.BasePcMktFeign;
import com.sumainfor.pc.gmio.service.RecycleHousingService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author Jack Chen
 * @Create 2019-01-23 17:57
 * 业主提前收房
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Log4j2
public class RecycleHousingServiceImpl implements RecycleHousingService {

    @Autowired
    private RecycleHousingMapper recycleHousingMapper;


    @Autowired
    private BaseFeignZuul feignZuul;

    @Autowired
    private BasePcMktFeign mktFeign;

    /**
     * 构建首页数据信息
     *
     * @param page
     * @param params 选择字段：
     *               Status - 审核状态    1 已确认  0 待沟通
     *               deptId - 服务中心编号
     *               Date - 时间筛选 yyyy-MM-dd
     * @return
     */
    @Override
    public JsonResult selectRecycleDataList(Page page, Map<String, Object> params) {
        IPage<Map<String, Object>> dataList = recycleHousingMapper.selectRecycleList(page, params);
        dataList.setRecords(dataList.getRecords().stream().map(item -> {
            //获得业主姓名
            Map<String, Object> ownerInfo = mktFeign.getOwnerInfoByParams(CustomMap.create("OwId", item.get("OwId")));
            if (MapUtils.isEmpty(ownerInfo)) {
                throw new TCException("没有查询到业主信息");
            }
            item.put("OwName", ownerInfo.get("OwName"));
            item.put("OwPhone", ownerInfo.get("OwPhone"));
            //获取房源信息
            //1. 项目名称 2. 楼号 室号 拆分数
            Map<String, Object> houData = mktFeign.getOmHousingInfoById(MapUtils.getString(item, "HouId"));
            item.putAll(houData);
            item.put("AcceptName", "-");
            if (StringUtils.isNotBlank(MapUtils.getString(item, "AcceptId"))) {
                JsonResult<List<Map<String, Object>>> userInfo = feignZuul.getUserInfo(Arrays.asList(MapUtils.getString(item, "AcceptId")));
                if (!userInfo.isSuccess() || CollectionUtils.isEmpty(userInfo.getResult())) {
                    throw new TCException("没有查询到受理人信息");
                }
                String username = (String) userInfo.getResult().get(0).get("username");
                item.put("AcceptName", username);
            }
            return item;
        }).collect(Collectors.toList()));
        return JsonResult.success(dataList);
    }

    /**
     * 获得所服务中心列表
     *
     * @return
     */
    @Override
    public JsonResult getCenterList() {
//        List<String> idList = recycleHousingMapper.getRecycleServiceCenterList();
        return JsonResult.success(feignZuul.getRecycleServiceCenter(Lists.newArrayList()));
    }

    /**
     * 业主提前收房提交申请
     *
     * @param params 必须字段：
     *               MiId 服务中心编号
     *               ComId 项目编号
     *               HouId 房源编号
     *               OwId 业主编号
     *               CallNumber 联系号码
     *               RecycleTime 期望收回时间 期望收回时间 时间格式(yyyy-MM-dd)
     * @return
     */
    @Override
    public JsonResult verifyRecycle(Map<String, Object> params) {
        Integer OwadvanceByOWIdAndHouId = getOwadvanceByOWIdAndHouId(params);
        if (OwadvanceByOWIdAndHouId > 0) {
            return JsonResult.error("已申请提前收房！");
        }
        String date = MapUtils.getString(params, "RecycleTime");
        Date dateTime = DateUtils.stringToDate(date, "yyyy-MM-dd");
        params.put("RecycleTime", dateTime);
        params.put("OwAdId", UUIDUtils.generateShortUuid());
        params.put("StartTime", DateTime.now().toDate());
        ParamsCommon.commonInsertParms(params, getClass());
        int row = recycleHousingMapper.verifyRecycleSubmit(params);
        return row <= 0 ? JsonResult.actionFailure() : JsonResult.actionSuccess();
    }

    /**
     * 功能描述:
     * 收房之前判断当前业主是否已申请收房
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/7/22 18:43
     */
    public Integer getOwadvanceByOWIdAndHouId(Map<String, Object> params) {
        return recycleHousingMapper.getOwadvanceByOWIdAndHouId(params);
    }


    ///////////////////////////////////////////////////////////////////////////
    // 业主信息变更审核
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 业主信息变更
     *
     * @param page
     * @param params type:
     *               1.房源-业主联系人变更
     *               2.房源-收款人变更表
     *               3.房源-业主成员变更表
     *               <p>
     *               选择字段：
     *               State - 审核状态    0 待审核  1已审核
     *               deptId - 服务中心编号
     * @return
     */
    @Override
    public JsonResult getTableByType(Page page, Map<String, Object> params) {
        Integer type = MapUtils.getInteger(params, "type");
        switch (type) {
            case 1:
                //房源-业主联系人变更
                params.put("table", "tcgmio_housing_owcontact");
                break;
            case 2:
                //房源-收款人变更表
                params.put("table", "tcgmio_housing_owpayee");
                break;
            case 3:
                //房源-业主成员变更表
                params.put("table", "tcgmio_housing_owmember");
                break;
            default:
                return JsonResult.error("没有这样的类型");
        }
        IPage<Map<String, Object>> pageRes = recycleHousingMapper.selectChangeDataByTypeAndParams(page, params);
        pageRes.setRecords(pageRes.getRecords().stream().map(item -> {
            //获得业主姓名
            Map<String, Object> ownerInfo = mktFeign.getOwnerInfoByParams(CustomMap.create("OwId", item.get("OwId")));
            if (MapUtils.isEmpty(ownerInfo)) {
                throw new TCException("没有查询到业主信息");
            }
            item.put("OwName", ownerInfo.get("OwName"));
            item.put("OwPhone", ownerInfo.get("OwPhone"));
            //获取房源信息
            //1. 项目名称 2. 楼号 室号 拆分数
            Map<String, Object> houData = mktFeign.getOmHousingInfoById(MapUtils.getString(item, "HouId"));
            item.putAll(houData);
            if (type.equals(3)) {
                //房源-业主成员变更表  查询详表数据信息
                List<Map<String, Object>> list = recycleHousingMapper.selectPeopleInfoListByMainId(MapUtils.getString(item, "MainId"));
                item.put("infoList", list.stream().map(img -> {
                    if (StringUtils.isNotBlank(MapUtils.getString(img, "IdnoImgs"))) {
                        List<Map<String, Object>> imgList = FileSubufferUtils.StringTranListUtils(MapUtils.getString(img, "IdnoImgs"));
                        img.put("IdnoImgs", imgList);
                    } else {
                        img.put("IdnoImgs", Lists.newArrayList());
                    }
                    return img;
                }).collect(Collectors.toList()));
            }

            //获取审核人名称
            String auditId = MapUtils.getString(item, "AuditId");
            item.put("AutoName", "-");
            if (StringUtils.isNotBlank(auditId)) {
                //查询
                JsonResult<List<Map<String, Object>>> json = feignZuul.getUserInfo(Arrays.asList(auditId));
                if (!json.isSuccess() || CollectionUtils.isEmpty(json.getResult())) {
                    throw new TCException("获取人员信息失败");
                }
                item.put("AutoName", json.getResult().get(0).get("username"));
            }
            return item;
        }).collect(Collectors.toList()));
        return JsonResult.success(pageRes);
    }

    /**
     * 业主信息变更审核通过
     *
     * @param id   主键ID
     * @param type 类型：
     *             1.房源-业主联系人变更
     *             2.房源-收款人变更表
     *             3.房源-业主成员变更表
     * @return
     */
    @Override
    public JsonResult verifySuccess(Integer id, Integer type) {
        String tableName;
        JsonResult result;
        switch (type) {
            case 1:
                //房源-业主联系人变更
                tableName = "tcgmio_housing_owcontact";
                break;
            case 2:
                //房源-收款人变更表
                tableName = "tcgmio_housing_owpayee";
                break;
            case 3:
                //房源-业主成员变更表
                tableName = "tcgmio_housing_owmember";
                break;
            default:
                return JsonResult.error("没有这样的类型");
        }
        int row = recycleHousingMapper.updateChangeVerifySuccess(id, tableName, ContextUtils.getUserId());
        if (row <= 0) {
            return JsonResult.error("审核失败");
        }
        Map<String, Object> map = recycleHousingMapper.selectChangeData(id, tableName);
        switch (type) {
            case 1:
                //房源-业主联系人变更
                result = mktFeign.updateOwCallInfo(map);
                break;
            case 2:
                //房源-收款人变更表
                result = mktFeign.updateOwPactInfo(map);
                break;
            case 3:
                //房源-业主成员变更表
                //查询 从表数据 获取
                List<Map<String, Object>> list = recycleHousingMapper.selectPeopleInfoListByMainId(MapUtils.getString(map, "MainId"));
                result = mktFeign.updateOwPeopleInfo(list.stream().map(iv2 -> {
                    iv2.putAll(map);
                    return iv2;
                }).collect(Collectors.toList()));
                break;
            default:
                result = JsonResult.error("没有这样的类型");
        }

        if (result.isSuccess() == false) {
            throw new TCException(result.getErrorMessage());
        }
        return result;
    }


    ///////////////////////////////////////////////////////////////////////////
    // 变更发起 - 提前收房申请
    ///////////////////////////////////////////////////////////////////////////


    /**
     * 通过业主手机号码去搜索业主的信息
     *
     * @param ownerPhone
     * @return
     */
    @Override
    public JsonResult searchOwnerInfo(String ownerPhone) {
        List<Map<String, Object>> infoList = mktFeign.getOwnerInfoListByPhone(ownerPhone);
        if (CollectionUtils.isEmpty(infoList)) {
            return JsonResult.error("没有找到业主信息");
        }
        Map<String, Object> info = infoList.get(0);
        CustomMap data = CustomMap.create("OwName", info.get("OwName"));
        List<Map<String, Object>> pactList = mktFeign.selectOwnerPactList(infoList.stream().map(o -> MapUtils.getString(o, "OwId")).collect(Collectors.toList()));
        data.put("dataList", pactList);
        return JsonResult.success(data);
    }


    /**
     * 通过业主编号查询这个业主的房源所在地理位置
     *
     * @param signOwnerId
     * @return
     */
    @Override
    public JsonResult getAddressInfo(String signOwnerId) {
        return JsonResult.success(mktFeign.getAddressInfo(signOwnerId));
    }

    /**
     * 变更发起 联系人信息
     *
     * @param params 必须字段：
     *               <p>
     *               <p>
     *               OldContact 原联系人姓名
     *               OldPhone 原联系人电话
     *               NewContact 现联系人姓名
     *               NewPhone 现联系人电话
     * @return
     */
    @Override
    public JsonResult submitChangeCallInfo(Map<String, Object> params) {
        params.put("CheckState", 0);
        params.put("AuditId", ContextUtils.getUserId());
        params.put("AuditTime", DateTime.now().toDate());
        int row = recycleHousingMapper.insertOwnerCallInfo(ParamsCommon.commonUpdateParms(params, getClass()));
        return row <= 0 ? JsonResult.actionFailure() : JsonResult.actionSuccess();
    }


    /**
     * 获取业主人员信息变更的原始数据
     *
     * @param houId
     * @return
     */
    @Override
    public JsonResult getOwnerPeopleData(String houId) {
        return JsonResult.success(mktFeign.getOwnerPeopleData(houId).stream().map(item -> {
            List<Map<String, Object>> list = FileSubufferUtils.StringTranListUtils(MapUtils.getString(item, "IdnoImgs"));
            item.put("IdnoImgs", list);
            return item;
        }).collect(Collectors.toList()));
    }

    /**
     * 变更发起提交改变业主人员信息
     *
     * @param params main:必须字段:
     *               MiId 服务中心编号
     *               ComId 项目编号
     *               HouId 房源编号
     *               OwId 业主编号
     * @return
     */
    @Override
    public JsonResult submitOwnerPeopleChange(Map<String, Object> params) {
        //创建主表数据
        String mainId = UUIDUtils.generateShortUuid();
        ParamsCommon.commonInsertParms(params, getClass());
        params.put("MainId", mainId);
        params.put("CheckState", 0);
        params.put("ChangeUserName", ContextUtils.getUserId());
        params.put("ChangeTime", DateTime.now().toDate());
        int row = recycleHousingMapper.insertOwnerPeopleMain(params);
        if (row <= 0) {
            return JsonResult.error("提交失败");
        }
        //循环子数据
        List<Map<String, Object>> list = (List<Map<String, Object>>) params.get("dataList");
        if (CollectionUtils.isEmpty(list)) {
            throw new TCException("请传入改变的数据");
        }
        for (Map<String, Object> map : list) {
            //从表需要的字段
            String[] key = {"OperType"};
            if (!FieldCheckUtil.isMapFieldNotNull(map, key)) {
                throw new TCException("dataList 参数不完整错误");
            }
            if (Objects.equals(MapUtils.getInteger(map, "OperType"), 2)) {
                if (StringUtils.isBlank(MapUtils.getString(map, "HouOwId"))) {
                    throw new TCException("dataList 参数不完整错误");
                }
            } else if (Objects.equals(MapUtils.getInteger(map, "OperType"), 1)) {
                if (!FieldCheckUtil.isMapFieldNotNull(map, "IdnoImgs", "IdnoNumber", "HouOwName")) {
                    throw new TCException("dataList 参数不完整错误");
                }
                map.put("IdnoImgs", FileSubufferUtils.ListTranStringUtils(((List) map.get("IdnoImgs"))));
            }
            map.put("MainId", mainId);
            map.put("IdnoType", 1);
            ParamsCommon.commonInsertParms(map, getClass());
            row = recycleHousingMapper.insertOwnerPeopleInfo(map);
            if (row <= 0) {
                throw new TCException("提交数据出现未知异常");
            }
        }
        return JsonResult.actionSuccess();
    }

    /**
     * 根据业主信息 去查询业主原来的收款信息
     *
     * @param owId
     * @return
     */
    @Override
    public JsonResult getOwnerOldBlankInfo(String owId) {
        return JsonResult.success(mktFeign.getOwnerOldBlankInfo(owId));
    }


    /**
     * 变更发起提交改变业主收款信息
     *
     * @param params 必须的字段：
     *               MiId 服务中心编号
     *               ComId 项目编号
     *               HouId 房源编号
     *               OwId 业主编号
     *               NewPayee 现收款人姓名
     *               NewPayAccount 现收款人银行账号
     *               NewPayBank 现收款人收款银行
     * @return
     */
    @Override
    public JsonResult submitBlankInfo(Map<String, Object> params) {
        ParamsCommon.commonInsertParms(params, getClass());
        params.put("CheckState", 0);
        params.put("ChangeUserName", ContextUtils.getUserId());
        params.put("ChangeTime", DateTime.now().toDate());

        JsonResult<Map<String, Object>> result = this.getOwnerOldBlankInfo(MapUtils.getString(params, "OwId"));
        if (result.isSuccess() == false) {
            return JsonResult.error("没有查到业主的信息");
        }

        Map<String, Object> info = result.getResult();

        params.put("OldPayee", info.get("Payee"));
        params.put("OldPayAccount", info.get("PayAccount"));
        params.put("OldPayBank", info.get("PayBank"));

        int row = recycleHousingMapper.insertOwnerBlankInfo(params);
        return row <= 0 ? JsonResult.actionFailure() : JsonResult.actionSuccess();
    }

}
